package eCheque;


import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

public class Validator {

	
	/**
	 * Validates passwords.  A password must be between 8 and 15 characters
	 * and contain at least two numbers
	 * @param password
	 * @return
	 */
	public static boolean validatePassword(char[] password) {
		int digitCount = 0;
		if( password.length >= 8 && password.length <16) {
			for (char c : password) {
				if(Character.isDigit(c))
					digitCount++;
			}
			if (digitCount >= 2)
				return true;
		}
		return false;
	}
	
	/**
	 * Since the user input can be a IP or URL, check to see if it's an IP
	 * then if it's not, check to see if it's a URL
	 * @param ip
	 * @return
	 */
	public static boolean validateIP(String ip) {
		if(ip.equals("localhost"))
			return true;
		String [] parts = ip.split ("\\.");
		if (parts.length != 4)
			return validateURL(ip);
        for (String s : parts)
        {
            int i = Integer.parseInt (s);
            if (i < 0 || i > 255) {
                return validateURL(ip);
            }
        }
        return true;
	}
	
	/**
	 * Checks to see if a URL is valid or not.
	 * @param urlString
	 * @return
	 */
	public static boolean validateURL(String urlString) {
		try {
			//Constructor throws an exception if the url given is invalid
		    URL url = new URL(urlString);
		} catch (MalformedURLException e) {
		    return false;
		} 
		return true;
	}
	
	public static boolean validateAmount(String amount) {
		try {
		if(Double.parseDouble(amount) > 0)
			return true;
		return false;
		} catch(Exception e) {
			return false;
		}
	}
	
	/**
	 * Checks to make sure an account number only contains valid digits
	 * @param accountNumber
	 * @return
	 */
	public static boolean validateAccountNumber(String accountNumber) {
		for(int i = 0; i < accountNumber.length(); i++) 
			if(!Character.isDigit(accountNumber.charAt(i)))
				return false;
		return true;
	}
	
	public static boolean validateDate(String month, String day, String year) {
		try {
			int monthValue = Integer.parseInt(month);
			int dayValue = Integer.parseInt(day);
			int yearValue = Integer.parseInt(year);
			
			if(monthValue > 0 && monthValue < 13
					&& dayValue > 0 && dayValue < 32
					&& yearValue > 1000 && yearValue < 3000) {
				return true;
			}
		} catch(NumberFormatException e) {
			//fall through and return false
		}
		return false;
	}
	
	public static boolean validateUserName(String userName) {
		if(userName.length() >0 && userName.length() < 91)
			return true;
		return false;
	}
}
